package thread.callback.guava;

import com.google.common.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class GuavaCallBack {

    public static void main(String[] args) {
        //Java线程池
        ExecutorService jPool = Executors.newFixedThreadPool(10);
        // Guava线程池
        ListeningExecutorService gPool = MoreExecutors.listeningDecorator(jPool);

        HotWaterJob hJob = new HotWaterJob();

        //submit()方法用来提交任务，返回异步任务实例
        ListenableFuture<Boolean> hFuture = gPool.submit(hJob);

        //绑定回调实例
        Futures.addCallback(hFuture, new FutureCallback<Boolean>() {
            @Override
            public void onSuccess(@Nullable Boolean result) {
                log.info("hFuture isDone {}",hFuture.isDone());
                log.info("");
            }

            @Override
            public void onFailure(Throwable t) {

            }
            //有两种实现回调的方法
        }, gPool);



    }

    static class HotWaterJob implements Callable<Boolean> //①
    {
        @Override
        public Boolean call() throws Exception //②
        {
            try {
//                log.info("洗好水壶");
                log.info("烧开水");

                //线程睡眠一段时间，代表烧水中
                Thread.sleep(10000);
                log.info("水开了");

            } catch (InterruptedException e) {
                log.info(" 发生异常被中断.");
                return false;
            }
            log.info(" 烧水工作，运行结束.");

            return true;
        }

    }

}
